//
//  AppDelegate.m
//  SquashApp
//
//  Created by DonKikochan on 21/01/13.
//  Copyright (c) 2013 Owlab. All rights reserved.
//

#import "AppDelegate.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    
    // Override point for customization after application launch.
    imagesCache = [NSMutableDictionary dictionaryWithCapacity:100];

    
    return YES;
}
							
- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}



#pragma mark - Custom functions

+ (AppDelegate*) mainAppDelegate
{
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}

- (void) downloadImageImmediateFromUrl:(NSString*)url forImageView:(UIImageView*)view andTag:(int)tag
{
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    UIImage *img = [imagesCache objectForKey:url];
    if (img != nil)
        view.image = img;
    else
    {
        if (tag >= 0)
            view.tag = tag;
        
        NSDictionary *data = [NSDictionary dictionaryWithObjectsAndKeys:
                              url, @"url",
                              view, @"view",
                              nil, @"indicator",
                              [NSString stringWithFormat:@"%d",tag], @"tagg",
                              nil];
        [self downloadImageWithObj:data];
    }
}


- (void) downloadImageFromUrl_Button:(NSString*)url forButton:(UIButton*) button
{
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    UIImage *img = [imagesCache objectForKey:url];
    if (img != nil)
    {
        [button setImage:img forState:UIControlStateNormal];
        [button setEnabled:TRUE];
    }
    else
    {
        [button setEnabled:FALSE];
        @try
        {
            
            UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(button.frame.size.width / 2 - 10, button.frame.size.height / 2 - 10, 20, 20)];
            indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
            [indicator startAnimating];
            [button addSubview:indicator];
            
            NSDictionary *data = [NSDictionary dictionaryWithObjectsAndKeys:
                                  url, @"url",
                                  button, @"button",
                                  indicator, @"indicator",
                                  nil];
            
            [self performSelectorInBackground:@selector(downloadImageWithObj_Button:) withObject:data];
        }
        @catch (NSException *exception)
        {
            NSLog(@"%@", exception);
        }
    }
}

- (void) downloadImageWithObj_Button:(NSDictionary*)data
{
    @autoreleasepool
    {
        @try
        {
            NSString *url = [data objectForKey:@"url"];
            //url = @"http://demos.endepro.com//weride////files//d73e1a5e4bbb036dd669edf4d553666d.";
            UIButton *button = [data objectForKey:@"button"];
            UIActivityIndicatorView *indicator = [data objectForKey:@"indicator"];
            
            //Check if it has been downloaded by another thread
            UIImage *img = [imagesCache objectForKey:url];
            if (img == nil)
            {
                NSURL *mapurl = [[NSURL alloc] initWithString:url];
                NSData *mapdata = [[NSData alloc] initWithContentsOfURL:mapurl];
                
                if (mapdata != nil)
                {
                    img = [[UIImage alloc] initWithData:mapdata];
                    
                    [imagesCache setValue:img forKey:url];
                }
            }
            
            if (img != nil)
            {
                [button setEnabled:TRUE];
                [button setImage:img forState:UIControlStateNormal];
            }
            
            [indicator removeFromSuperview];
        }
        @catch (NSException *exception)
        {
            NSLog(@"%@", exception);
        }
    }
}


- (void) downloadImageFromUrl:(NSString*)url forImageView:(UIImageView*)view andTag:(int)tag
{
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    UIImage *img = [imagesCache objectForKey:url];
    if (img != nil)
        view.image = img;
    else
    {
        @try
        {
            if (tag >= 0)
            {
                view.tag = tag;
                view.image = [UIImage imageNamed:@"4-tablecell-no-avatar-image.png"];
            }
            
            UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(view.frame.size.width / 2 - 10, view.frame.size.height / 2 - 10, 20, 20)];
            if (tag >= 0)
                indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
            else
                indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
            [indicator startAnimating];
            [view addSubview:indicator];
            
            NSDictionary *data = [NSDictionary dictionaryWithObjectsAndKeys:
                                  url, @"url",
                                  view, @"view",
                                  indicator, @"indicator",
                                  [NSString stringWithFormat:@"%d",tag], @"tagg",
                                  nil];
            
            [self performSelectorInBackground:@selector(downloadImageWithObj:) withObject:data];
        }
        @catch (NSException *exception)
        {
            NSLog(@"%@", exception);
        }
    }
}

- (void) downloadImageWithObj:(NSDictionary*)data
{
    @autoreleasepool
    {
        @try
        {
            NSString *url = [data objectForKey:@"url"];
            UIImageView *view = [data objectForKey:@"view"];
            UIActivityIndicatorView *indicator = [data objectForKey:@"indicator"];
            NSString *tag = [data objectForKey:@"tagg"];
            
            //Check if it has been downloaded by another thread
            UIImage *img = [imagesCache objectForKey:url];
            if (img == nil)
            {
                NSURL *mapurl = [[NSURL alloc] initWithString:url];
                NSData *mapdata = [[NSData alloc] initWithContentsOfURL:mapurl];
                
                if (mapdata != nil)
                {
                    img = [[UIImage alloc] initWithData:mapdata];
                    
                    [imagesCache setValue:img forKey:url];
                }
            }
            
            int tagVal = [tag intValue];
            if (img != nil && (tagVal < 0 || view.tag == tagVal))
                view.image = img;
            
            [indicator removeFromSuperview];
        }
        @catch (NSException *exception)
        {
            NSLog(@"%@", exception);
        }
    }
}

- (void) removeURLFromCache:(NSString*)url
{
    [imagesCache removeObjectForKey:url];
}


@end
